<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\utils\JsonResponse;
use think\App;
use think\facade\Request;
use app\common\model\OperationLog as OperationLogModel;

/**
 * @NoLog
 */
class OperationLog extends AdminController
{
    protected OperationLogModel $logModel;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->logModel = new OperationLogModel();
    }

    /**
     * 获取日志列表
     * @permission monitor:log:query
     * @NoLog
     */
    public function getList()
    {
        $params = Request::get();

        try {
            // 标准化分页参数
            $pageNo = isset($params['pageNo']) ? intval($params['pageNo']) : 1;
            $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 10;

            // 查询条件
            $where = [];

            // 请求方法
            if (!empty($params['method'])) {
                $where[] = ['method', '=', $params['method']];
            }

            // 时间范围
            if (!empty($params['dateRange'])) {
                $where[] = ['create_time', 'between', $params['dateRange']];
            }

            // 查询列表
            $list = $this->logModel
                ->where($where)
                ->field('log_id,method,url,ip,browser,os,code,cost_time,create_time')
                ->order('log_id', 'desc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $pageNo
                ]);

            return JsonResponse::successPaginate($list);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 获取日志详情
     * @permission monitor:log:getDetail
     * @NoLog(params=true,result=true)
     */
    public function getDetail()
    {
        $params = Request::get();

        try {
            $data = $this->logModel
                ->field('log_id,url,method,request_header,params,response_header,result,ip,browser,os,code,error_msg,cost_time,extend,create_time')
                ->find($params['log_id']);

            if (!$data) {
                return JsonResponse::error('日志不存在');
            }

            return JsonResponse::success($data);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
}
